<template>
    <div id="addWrap" v-loading="loading" class="sc-form-table">
        <div style="padding:15px 20px 10px;background-color:#fff;
    box-shadow: rgb(204, 204, 204) 0px 1px 4px;" id='header'>
            <el-dropdown @command="handleCommand">
            <el-button type="primary" :disabled="template.modelTitle==''|| template.modelId==''" style="margin-right: 3px;">
                新建问题<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown" :class="{hide:template.modelTitle==''|| template.modelId==''}">
                <el-dropdown-item command="1_n">单选题</el-dropdown-item>
                <el-dropdown-item command="2_n">多选题</el-dropdown-item>
                <el-dropdown-item command="3_n">问答题</el-dropdown-item>
            </el-dropdown-menu>
            </el-dropdown>
            <!-- <el-button type="primary" @click="saveSort">保存</el-button> -->
            <el-button type="primary" :disabled="data.length===0" @click="onView">预览</el-button>
            <el-button @click="back">返回</el-button>
        </div>
        <div class="formWrap">
            <div style="padding:20px 0 60px;max-width: 960px; background: #fff;margin: 20px  auto;min-height: 600px;">
            <div style="padding: 20px 40px;">
                    <el-input v-model="template.modelTitle" placeholder="请输入模版标题" class="tempName"  maxlength="20" @change="creatTem"></el-input>
                </div>
            <el-form :model="ruleForm" :rules="rules" ref="allRuleForm" label-width="130px">
                <div  class="allRuleForm">
                   <div v-for="(item, index) in data" :key="index" class="divMove questionWrap" >
                    <div :class="['el-form-item', {'is-required':item.is_required}, 'questionSinggle']" style="margin-bottom: 10px;">
                        <div class="questionLabel" v-text= "((index + 1) < 10 ? '0' + (index + 1) : (index + 1))+'.'" ></div>
                        <div class="questionContent" >
                            <el-tag  size="mini" effect="plain" style="margin-right: 10px;">{{ questionType[item.type]}}</el-tag>{{item.question_title}}?
                        </div>
                    </div>
                    <div class="questionTip">{{item.description}}</div>
                    <div class="imagePreviewWrap">
                        <div v-for="(ite, i) in item.pic" :key="i">
                            <el-image
                                style="width: 72px; height: 72px;margin-left: 3px;margin-bottom: 3px;"
                                :src="ite"
                                :preview-src-list="item.pic">
                            </el-image>
                        </div>
                    </div>
                    <div v-if="Number(item.type) == 1" style="padding-left: 40px;">
                        <!-- <el-radio-group v-model="item.answer"> -->
                            <div v-for="(it, i) in item.option_json" :key="i"
                                    style="display: flex;align-items: center;padding-bottom: 8px;">
                                    <el-radio label="" style="width: 20px; margin: 0; pointer-events: none;"></el-radio>
                                    <div style="width:180px;">{{ allSN[i] }}.{{it.name}} <el-tag v-if="item.is_score==1" size="small">{{it.score+'分'}}</el-tag></div>
                                    <div  style="width:180px;">{{it.related?'显示'+idAdd(it.related)+'题':'-'}}</div>
                                    <el-link style="margin-right:10px" v-if="!hideDelete" plain @click="rowSet(item,it, index,i)" type="primary">关联选项</el-link>
                                    <el-link v-if="item.related" plain @click="optionDel(item,it, index)" type="danger">清空已选</el-link>
                            </div>
                        <!-- </el-radio-group> -->
                    </div>
                    <div v-if="Number(item.type) == 2" style="padding-left: 40px;">
                            <div v-for="(it, i) in item.option_json" :key="i"
                                    style="display: flex;align-items: center;padding-bottom: 8px;">
                                    <el-checkbox style="width: 20px; margin: 0; pointer-events: none;"></el-checkbox>
                                    <div style="width:180px">{{ allSN[i] }}.{{it.name}}</div>
                                    <div style="width:180px;">{{it.related?'显示'+idAdd(it.related):'-'}}</div>
                                    <el-link style="margin-right:10px;" v-if="!hideDelete" plain @click="rowSet(item,it, index,i)" type="primary">关联选项</el-link>
                                    <el-link v-if="item.related" plain @click="optionDel(item,it, index)" type="danger">清空已选</el-link>
                            </div>
                    </div>
                    <div v-if="Number(item.type) == 3 && !item.is_score" >
                        <div class="question-body" style="padding-left: 38px;"><input class="inputs-input" type="text" placeholder="待填写者填写" value=""></div>
                    </div>

                    
                    <div v-if="Number(item.type) == 3 && item.is_score" class="questionTip">
                        <el-slider v-model="item.answer" :min="item.limit_min" :max="item.limit_max" ></el-slider>
                        <!-- <div class="question-body" style="padding-left: 38px;"><input class="inputs-input" type="text" placeholder="待填写者填写" value=""></div> -->
                    </div>

                    <div v-if="Number(item.type) == 2" class="questionSelectionTip">
                         {{ MCQSelectionText(item.limit_min,item.limit_max)}}
                    </div>
                    <div v-if="Number(item.type) == 3 && item.is_score" class="questionSelectionTip">
                         计分题{{ subjectiveInputText(item.limit_min,item.limit_max)}}
                    </div>
                    <div class="tool">
                        <el-dropdown @command="handleCommand">
                        <span class="el-dropdown-link">
                            插入问题<i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <!-- <el-link slot="reference" type="primary" class="tool-item" title="编辑当前题目" @click="add(item,index,0)">插入问题 <i class="el-icon-arrow-down el-icon--right"></i></el-link> -->
                        <el-dropdown-menu slot="dropdown" :append-to-body="false" style="width: 90px;">
                            <el-dropdown-item :command="'1_'+index">单选题</el-dropdown-item>
                            <el-dropdown-item :command="'2_'+index">多选题</el-dropdown-item>
                            <el-dropdown-item :command="'3_'+index">问答题</el-dropdown-item>
                        </el-dropdown-menu>
                        </el-dropdown>

                        <el-link slot="reference" type="primary" class="tool-item" title="编辑当前题目" @click="editQuestion(item,index,0)">编辑 </el-link>
                        <el-link slot="reference" type="primary" class="tool-item" title="复制当前题目" @click="editQuestion(item,index,2)">复制 </el-link>
                        <el-popconfirm :title="item.is_statistics!==1?'确定要删除当前题目吗？':'删除统计项目后，请假明细表将不能对此题目进行数据筛选'" @confirm="delQuestion(item,index)">
                            <el-link slot="reference" class="tool-item" type="danger" title="删除当前题目">删除
                            </el-link>
                    </el-popconfirm>
                    </div>
                </div>
            </div>
                <!-- <el-button type="primary" @click="onSubmit">保存</el-button> -->
                <!-- <el-button @click="open">取消</el-button> -->
            </el-form>
        </div>
        </div>
        <!-- 预览模板 -->
        <el-dialog title="预览模板" :visible.sync="dialogVisible" width="440px" height='774' id="viewWrap" custom-class="viewWrap" style="margin-top:-10vh;">
            <div  id="completeDiv" ref="completeDiv" class='viewBG' >
              <iframe ref="myIframe" :src="completeTask"  width="100%" style="border:none; height: 100%;"></iframe>
            </div>
        </el-dialog>

        <el-dialog title="可关联题目（可多选）" :visible.sync="dialogRelated" width="480">
            <div class="formView">
                <div style="display:flex;justify-content: space-between;">
                    <div style="font-weight:bold;">{{nowRelatedQuestionInfo}}</div>
                    <el-button type="danger" @click="clearChanged" plain size="mini"
                        style=" padding: 0px 6px;">清空已选</el-button>
                </div>
                <el-checkbox-group v-model="relatedQuestion" style="display:block;" @change="handleCheckedOptionChange">
                    <div v-for="(item, i) in sortData" v-bind:key="i">
                        <div v-if="item.parent=='' || (item.parent!=='' && (relatedQuestion.includes(item.question_id)||relatedQuestion2.includes(item.question_id)))"
                            style="padding-bottom:5px;">
                            <el-checkbox :label="item.question_id" name="type"
                                :key="index+i + 1">{{(idAdd(item.question_id.toString())[0])+'.'+item.question_title}}?  </el-checkbox>
                        </div>
                    </div>
                </el-checkbox-group>
                <!-- :disabled="(idAdd(item.id.toString())[0])<9" -->
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveRelation">确 认</el-button>
                <el-button @click="dialogRelated=false">取 消</el-button>
            </span>
        </el-dialog>

        <!-- 编辑新建题目 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogEdit" width="40%" v-loading="editLoading" append-to-body lock-scroll destroy-on-close @close="clearData">
            <div class="formView">
                <el-form ref="ruleForm" :model="form" >
                    <el-form-item label="题目" prop="question_title" :rules="{required: true, message: '当前题目不能为空！', trigger: 'blur'}">
                        <el-input v-model="form.question_title" maxlength="50" placeholder="请输入题目内容" style="width: 500px;"></el-input> ?
                    </el-form-item>
                    <el-form-item label="提示文字" v-if="Number(form.type)!==7">
                        <!-- <el-input v-model="form.description" maxlength="100" placeholder="请输入提示文字"></el-input> -->
                        <el-input type="textarea" v-model="form.description" maxlength="100" show-word-limit rows="3" placeholder="请输入提示文字" style="width: 500px;"></el-input>
                    </el-form-item>
                    <el-form-item label="" prop="pic" class="imgListWrap">
                        <el-upload :file-list="form.pic" accept=".jpg, .png, .gif" :on-change="handleChange" :on-preview="handlePreview"  :on-remove="handleDel" action="" :http-request="upImg" list-type="picture-card" draggable :limit="3" :maxSize="30"
                            tip="最多上传9个文件,单个文件不要超过30M,请上传图像格式文件" :class="{imgHide:form.pic.length>=3}">
                            <i slot="default" class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="是否必填">
                        <el-checkbox v-model="form.is_required" style="width:20px;margin-top:3px;"></el-checkbox>
                    </el-form-item>
                    <el-form-item label="是否记分" v-if="Number(form.type)==3||(form.type)==1">
                        <el-checkbox v-model="form.is_score" style="width:20px;margin-top:3px" @change="scoreChange"></el-checkbox>
                    </el-form-item>
                    <el-form-item label="分数限制" v-if="Number(form.type)==3 && form.is_score ">
                        <el-input  v-model="form.limit_min" style="width:118px;" maxlength="9" placeholder="请输入正整数" @blur='checkedNum($event,form,"limit_min")'></el-input >
                            ≤ 输入数字 ≤
                        <el-input  v-model="form.limit_max" style="width:118px;" maxlength="9" placeholder="请输入正整数" @blur='checkedNum($event,form,"limit_max")'></el-input >
                    </el-form-item>
                    <el-form-item label="选择限制" v-if="Number(form.type)==2 ">
                        <el-input  v-model="form.limit_min" style="width:118px;" maxlength="9" placeholder="请输入正整数" @blur='checkedNum($event,form,"limit_min")'></el-input >
                            ≤ 选择个数 ≤
                        <el-input  v-model="form.limit_max" style="width:118px;" maxlength="9" placeholder="请输入正整数" @blur='checkedNum($event,form,"limit_max")'></el-input >
                    </el-form-item>
                    <!-- 提示文字 -->
                    <!-- <transition name="bounce">
                        <el-link style="padding-left:20px" :underline="false"
                            v-if="Number(form.type)==3||(form.type)==7"
                            type="info">{{Number(form.type)==3?'最大可输入字符：50个字':Number(form.type)==7?'最多可上传9张图片':''}}</el-link>
                    </transition> -->
                    <div v-if="Number(form.type)==2||(form.type)==1" ref="questionOptionWrap">
                        <el-form-item label="选项">
                            <div v-if="form.type==1">
                                <el-radio-group v-model="form.default">
                                    <el-table  ref="option" style="width: 100%" :data="form.option_json" border align="center" show-overflow-tooltip highlight-current-row stripe table-layout='auto'>
                                        <el-table-column label="" width="50" style="cursor: move;">
                                            <template #default>
                                            <div class="move"><i class="el-icon-d-caret" style="width: 1em; height: 1em;"></i> </div>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="序号" type="index" width="50"  align="center">
                                            <template slot-scope="scope">
                                            {{allSN[scope.$index]}}
                                            </template>
                                        </el-table-column>
                                        <el-table-column  label="问题" width="240"  align="center">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.name" maxlength="10" placeholder="请输入选项内容"></el-input>
                                            </template>
                                        </el-table-column>
                                            <el-table-column v-if="Number(form.type)==3||(form.type)==1" label="分数"  align="center">
                                                <template slot-scope="scope">
                                                    <el-input v-model="scope.row.score" maxlength="10" :disabled="form.is_score==0" placeholder="分数" @keyup.native='checkedNum($event,scope.row,"score")'></el-input>
                                                </template>
                                            </el-table-column>
                                        <el-table-column  label="默认选中"  width="80"  align="center">
                                            <template slot-scope="scope">
                                            <el-radio :label="scope.$index">
                                                <span v-show="false"></span>
                                            </el-radio>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="操作" align="center">
                                        <template slot-scope="scope">
                                            <el-popconfirm title="确定删除该选项吗？" @confirm="delOption(form.option_json,scope.$index)">
                                            <el-link type="danger" slot="reference" size="small" :title="'删除【'+scope.row.name +'】'">删除</el-link>
                                            </el-popconfirm>
                                        </template>
                                        </el-table-column>
                                    </el-table>
                                </el-radio-group>
                            </div>
                            <div v-if="form.type==2">
                                <el-table ref="option" style="width:100%;" :data="form.option_json" border align="center" show-overflow-tooltip highlight-current-row stripe table-layout='auto'>
                                    <el-table-column label="" width="50" style="cursor: move;">
                                        <template #default>
                                        <div class="move"><i class="el-icon-d-caret" style="width: 1em; height: 1em;"></i> </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="序号" type="index" width="50"  align="center">
                                        <template slot-scope="scope">
                                        {{allSN[scope.$index]}}
                                        </template>
                                    </el-table-column>
                                    <el-table-column  label="问题" width="240"  align="center">
                                        <template slot-scope="scope">
                                            <el-input v-model="scope.row.name" maxlength="10" placeholder="请输入选项内容"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column  label="默认选中"  width="80"  align="center">
                                        <template slot-scope="scope">
                                        <el-checkbox v-model="scope.row.checked" style="width: 20px; margin: auto;" @change="multipleChoice($event,scope.row,form)"></el-checkbox>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="操作"  align="center">
                                    <template slot-scope="scope">
                                        <el-popconfirm title="确定删除该选项吗？"  @confirm="delOption(form.option_json,scope.$index)">
                                        <el-link type="danger" slot="reference" size="small" :title="'删除【'+scope.row.name +'】'" >删除</el-link>
                                        </el-popconfirm>
                                    </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                            <el-button v-if="form.option_json.length < 26" type="primary" icon="el-icon-plus" size="small"
                            circle @click="rowOption(form.option_json)" title="新增选项" class="addOptionBtn" ></el-button>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="onSubmit">保存</el-button>
                <el-button @click="dialogEdit=false">取 消</el-button>
            </span>
        </el-dialog>
        <el-dialog title="dialogTitle" :visible.sync="dialogView" width="414">
        </el-dialog>
        <el-dialog :visible.sync="dialogImgViewVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
     </div>
</template>
<script>
import Sortable from 'sortablejs'
export default {
    name:'addModel',
    data() {
        return {
            ruleForm: {
                'id': '',
                'template_name': '',
                'template_json': '',
                'open_btn': 1,
                'is_seal': '1'
            },
            template: {
                modelTitle: '',
                modelId: ''
            },
            allSN: {},
            questionType: {
                1: '单选题',
                2: '多选题',
                3: '问答题'
            },
            rules: {
                template_name: [
                    { required: true, message: '请填写模板名称', trigger: 'blur' }
                ],
                is_seal: [
                    { required: true, message: '请选择', trigger: 'blur' }
                ]
            },
            // 题校验
            questionRules: {
                question_title: [
                    { required: true, message: '请填写模板名称', trigger: 'blur' }
                ]
            },
            allOption: [{
                name: ''
            }],
            dialogTitle: '新增题目',
            addTemplate: {
                'question_title': '',
                'description': '',
                'question_id': '',
                'model_id': '',
                'pic': [],
                'type': 1,
                'is_score': false,
                'maxlength': '20',
                'limit_min': 1,
                'limit_max': 50,
                'is_required': true,
                'option_json': [{
                    'name': '',
                    'checked': true,
                    'related': '',
                    'score': '',
                    'value': 'A'
                }, {
                    'name': '',
                    'checked': false,
                    'related': '',
                    'score': '',
                    'value': 'B'
                }]
            },
            newOption: {
                'name': '新选项',
                'checked': false,
                'related': '',
                'score': '',
                'value': ''
            },
            data: [],
            dialogVisible: false,
            // 新建编辑题目窗口打开
            dialogEdit: false,
            // 关联窗口
            dialogRelated: false,
            // 当前设置关联的题号
            index: 0,
            hideDelete: false,
            loading: false,
            org_name: '',
            // 控制印章显示的标志
            sealShow: true,
            editLoading: false,
            time: '',
            // 新增表单
            form: {
                'question_title': '新增题目',
                'description': '请选择请假类型',
                'question_id': '',
                'type': '1',
                'is_score': 0,
                'pic': [],
                'limit_min': 1,
                'limit_max': 50,
                'sort_num': 1,
                'is_required': false,
                'default': 0,
                'option_json': [{
                    'name': '选项1',
                    'checked': true,
                    'related': '',
                    'score': '',
                    'value': 'A'
                }, {
                    'name': '选项2',
                    'checked': false,
                    'related': '',
                    'score': '',
                    'value': 'B'
                }]
            },
            sortData: [],
            // 关联相关操作
            // 当前关联
            relatedQuestion: [], // 已选择的关联
            relatedQuestion2: [], // 已选择的关联备份
            oldRelatedQuestion: [], // 取消关联不保存
            oldRelatedIndex: 0,
            // 当前关联题目信息
            nowRelatedQuestionInfo: null,
            nowRelatedInfo: null,
            editQuestionInfo: null,
            // 预览
            dialogView: false,
            completeTask: '',
            fileList: [],
            // 上传图片预览
            dialogImageUrl: '',
            dialogImgViewVisible: false
        }
    },
    mounted() {
        const _this = this
        // this.time = this.formattedTime()
        const editTemplate = sessionStorage.editTemplate;
    
        if (editTemplate && editTemplate !== 'null') {
            this.$parent.$parent.editTemplate = editTemplate;
            this.get(); // 直接在条件成立时调用get方法
        }

        //  生成26个字母
        for (let i=0; i<26; i++) {
            // 输出A-Z  26个大写字母
            this.allSN[i]=String.fromCharCode(65 + i)
        }

      // 吸顶效果
      const header = document.getElementById('header')
      const headerOriginalPos = header.offsetTop // 获取元素原来的位置

      window.addEventListener('scroll', function() {
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        if (scrollTop >= headerOriginalPos) {
          header.style.position = 'fixed'
          header.style.top = '60px'
          header.style.padding = '10px 20px 10px'
          header.style.width = '100%'
          header.style.zIndex = '999'
          header.style.boxShadow = '0px 1px 4px #ccc'
        } else {
          header.style.position = 'static'
          header.style.boxShadow = 'none'
        }
      })
       const hash=location.hash
       // 路由变化，执行数据加载，清空弹出层，时间框
        window.onhashchange = function (e) {
            if (hash !== location.hash) {
                _this.$confirm('确定要离开本页面吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        closeOnHashChange: false,
                        lockScroll: true,
                        closeOnClickModal: false,
                        type: 'warning'
                    }).then(() => {
                        window.location.reload()
                    }).catch(() => {
                        window.location.hash = hash
                })
            }
            return false
        }
    },
    created() {},
    computed: {},
    methods: {
        multipleChoice(val,option,question){
            // let sum=0
            // question.option_json.map(item=>{
            //     if(item.checked){
            //         sum+=1
            //     }
            // })
            // 计算选中的选项数量
            const sum=question.option_json.filter(item => item.checked).length
            if(sum>question.limit_max){
                option.checked=false
                this.$alert('默认选中项不能超过最大选择数', '提示', { type: 'warning', closeOnHashChange: !1 })
            }
        },
        // 格式化时间
        formattedTime() {
            const date = new Date()
            const year = date.getFullYear()
            // const month = ('0' + (date.getMonth() + 1)).slice(-2)
            // const day = ('0' + date.getDate()).slice(-2)
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year} 年 ${month} 月 ${day} 日`
        },
        // 下拉新增选项
        handleCommand(command) {
            const base =command.split('_')
            const questionType=base[0]
            const questionLocation=base[1]
            this.addQuestion(questionType, questionLocation)
        },
        scoreChange(val) {
         console.log(val)
         if (!val) {
            this.form.option_json.map(item => {
                item.score=''
            })
            if(this.form.type===3) {
                this.form.limit_max=50
                this.form.limit_min=1
            }
         }
        
        },
        // 创建模版
        async creatTem() {
            if (this.template.modelTitle ==='') {
                this.$alert('模版名称不能为空！', '提示', { type: 'warning', closeOnHashChange: !1 })
                return false
            }
            const res = await this.$api.add.add.post(this.template)
            if (res.code === 200) {
                // this.$message.success('保存成功')
                sessionStorage.editTemplate = res.data.modelId
                this.template.modelId = res.data.modelId
                this.$parent.$parent.editTemplate = res.data.modelId
                this.loading = false
            } else {
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
                this.loading = false
            }
        },
        // 显示多选题选择限制(multipleChoiceqQuestion)
        MCQSelectionText(min, max) {
            if (min === null || min === undefined) {
                min = '';
            } 
            if (max === null || max === undefined) {
                max = '';
            } 

            // else if (min !== '' && max ==='') {
            //     return '至少选择 '+ min +' 项'
            // } else if (min === '' && max !=='') {
            //     return '最多选择 ' + max + ' 项'
            // }
            if (min === '' && max ==='') {
                return '不限制可选数量'
            }  else {
                return '选择项数在两者之间，' + min + ' ≤ 选择数量 ≤' + max
            }
         },
         subjectiveInputText(min, max) {
            return '只能输入数字，输入数字在两者之间，' + min + ' ≤ 输入数量 ≤' + max
         },
        // 初始化可拖动表格
        tableAddClass({ row, rowIndex }) {
            if (row.is_fixed === 1) { return 'tr-grey' }
            return 'tr-move'
        },
        // 拖动排序
        rowDrop() {
            const _this = this
            const tbody = this.$refs.allRuleForm.$el.querySelector('.allRuleForm')
            Sortable.create(tbody, {
                handle: '.divMove',
                animation: 300,
                ghostClass: '.divMove',
                onEnd({ newIndex, oldIndex }) {
                     // 需要更新的数据
                    let needUpdateData = null
                    if (newIndex < oldIndex) {
                      // 关联项上移 例如：1题关联234，把第2题挪到第1个的位置
                      if (_this.data[oldIndex].parent !== '') {
                          // 如果挪动的新位置少于父级的位置（挪到了父级的上面,父级的关联子级的项取消且其他关联项更新，子级的父id为空，）
                          let oldParentId = _this.idAdd(_this.data[oldIndex].parent.toString())[0]
                          let oldId=_this.data[oldIndex].parent
                          if (newIndex < oldParentId) {
                              console.log(_this.data[oldParentId - 1])
                              // 父级的关联更新
                              let parentUpdateObject = _this.data[oldParentId - 1]

                              for (let a=0, b= parentUpdateObject.option_json.length; a<b; a++) {
                              // parentUpdateObject.option_json.map((item, index) => {
                                  const item=parentUpdateObject.option_json[a]
                                  let isBreak=false
                                  if (item.related !== '') {
                                      let temporaryArray = item.related ? item.related.split(',') : []
                                      for (let i = 0; i < temporaryArray.length; i++) {
                                          if (Number(temporaryArray[i]) === _this.data[oldIndex].question_id) {
                                              temporaryArray.splice(i, 1)
                                              _this.$alert('<div class="el-alert el-alert--warning is-light"><i class="el-alert__icon el-icon-warning"></i><div class="el-alert__content">调整顺序后，'+ (_this.idAdd(oldId.toString())[0]+1)+ '题选项'+ _this.allSN[a]+ '设置的关联有变化，可重新设置！</div></div>', {
                                                  title: '提示',
                                                  closeOnHashChange: !1,
                                                  dangerouslyUseHTMLString: true
                                              })
                                              _this.data[oldIndex].parent=''
                                              item.related = temporaryArray.join(',')
                                              isBreak=true
                                              break
                                          }
                                      }
                                  }
                                  if (isBreak) {
                                    break
                                  }
                              // })
                              }
                          }
                          needUpdateData = _this.data[oldParentId - 1]
                      }
                    }
                    if (newIndex >= oldIndex) {
                      // 被关联项下移 例如：1题关联234，把第一个题挪到第四个的位置
                      if (_this.data[oldIndex].option_json) {
                          _this.data[oldIndex].option_json.map((item, index) => {
                              console.log(item.related)
                              if (item.related !== '') {
                                  let temporaryArray = item.related.split(',')
                                  // 变化项
                                  let bh=[]
                                  // 保留项
                                  let newTemporary=[]
                                  for (let i = 0; i < temporaryArray.length; i++) {
                                      console.log(_this.idAdd(temporaryArray[i])[0])
                                      console.log(newIndex + 1)
                                      if (_this.idAdd(temporaryArray[i])[0] <= newIndex + 1) {
                                          _this.$alert('<div class="el-alert el-alert--warning is-light"><i class="el-alert__icon el-icon-warning"></i><div class="el-alert__content">调整顺序后，第'+ (newIndex + 1) + '题选项'+ _this.allSN[index]+ '设置的关联有变化，可重新设置！</div></div>', {
                                              title: '提示',
                                              closeOnHashChange: !1,
                                              dangerouslyUseHTMLString: true
                                          })
                                          bh.push(temporaryArray[i])
                                          // 变化项的父Id要去掉
                                          console.log(_this.data[_this.idAdd(temporaryArray[i])[0]-1])
                                          _this.data[_this.idAdd(temporaryArray[i])[0]-1].parent=''
                                      } else {
                                        newTemporary.push(temporaryArray[i])
                                      }
                                  }
                                  item.related = newTemporary.join(',')
                                  needUpdateData = _this.data[oldIndex]
                              }
                          })
                      }
                    }
                    // 保存更新数据
                    const changeQuestion = _this.data[oldIndex]
                    _this.data.splice(oldIndex, 1)
                    _this.data.splice(newIndex, 0, changeQuestion)
                    const ids = _this.data.map(item => item.question_id)
                    _this.data = []
                    _this.$nextTick(() => {
                        // 调用保存
                        _this.saveSort(needUpdateData, ids)
                    })
                }
            })
        },
        checkedNum(event, obj, field) {
            debugger
            const value = event.target.value.replace(/[^\d]/g, '');
            let dealObj = value === '' ? '' : Number(value);

            if (field) {
                obj[field]= dealObj;
            }

            // 限制最大最小值
            if ((field === 'limit_max' || field === 'limit_min') && dealObj > obj.option_json.length && obj.type === 2) {
                this.$message({
                    message: '最多只能选择' + obj.option_json.length + '！',
                    type: 'warning'
                });
                obj[field] = obj.option_json.length;
            }

            if (field === 'limit_min' && dealObj < 1 && (obj.type === 2||obj.type === 1)) {
                this.$message({
                    message: '至少选择1项！',
                    type: 'warning'
                });
                dealObj = 1;
            }

            // if (field === 'limit_min' && obj.type === 3 && dealObj < 1) {
            //     dealObj = '';
            // }

            // 进行范围校验
            if (field === 'limit_min' && Number(obj.limit_min) > Number(obj.limit_max)) {
                const tipStr = obj.type === 2 ? '最少选择项不能大于最多选择项！' : '输入最小数不能大于输入最大数！';
                this.$message({
                    message: tipStr,
                    type: 'warning'
                });
                obj.limit_min = '';
            }

            if (field === 'limit_max' && Number(obj.limit_min) > Number(obj.limit_max)) {
                const tipStr = obj.type === 2 ? '最多选择项不能小于最少选择项！' : '输入最大数不能小于于输入最小数！';
                this.$message({
                    message: tipStr,
                    type: 'warning'
                });
                obj.limit_max = '';
            }

            // 更新score属性
            if (!field) {
                obj.score = dealObj;
            } else if (field === 'score' && dealObj === '') {
                obj.score = '';
            }

            event.target.value = dealObj;

        //     debugger
        //     const value=event.target.value.replace(/[^\d]/g, '')
        //     if (event.target.value.replace(/[^\d]/g, '') ==='') {
        //         event.target.value= ''
        //         if (!field) {
        //             obj.score= ''
        //         }
        //     }

        //     let dealObj = field!==undefined && value!==''?Number(value):''

        //     if ((field ==='limit_max' || field ==='limit_min') && dealObj > obj.option_json.length && obj.type===2) {
        //         this.$message({
        //             message: '最多只能选择'+obj.option_json.length+'！',
        //             type: 'warning'
        //         })
        //         obj[field]=obj.option_json.length
        //     }
        //     if (field ==='limit_min' && dealObj<1 && obj.type===2) {
        //         this.$message({
        //             message: '至少选择1项！',
        //             type: 'warning'
        //         })
        //         dealObj=1
        //         obj['limit_min']= dealObj
        //     }

        //     // if (field ==='limit_max' && dealObj<2 && obj.type===2) {
        //     //     dealObj=''
        //     //     obj['limit_max']= dealObj
        //     // }

        //     if (field ==='limit_min' && dealObj<1 && obj.type===3) {
        //         dealObj=''
        //         obj['limit_min']= ''
        //     }

        //     if (field ==='limit_max' && dealObj<2 && obj.type===3) {
        //         dealObj=''
        //         obj['limit_max']= ''
        //     }

        //     if (Number(obj.limit_min) > Number(obj.limit_max) && field ==='limit_min'&&event.target.value!=='') {
        //         let tipStr=''
        //         if (obj.type===2) {
        //             tipStr='最少选择项不能大于最多选择项！'
        //         }
        //         if (obj.type===3) {
        //             tipStr='输入最小数不能大于输入最大数！'
        //         }
        //         this.$message({
        //             message: tipStr,
        //             type: 'warning'
        //         })
        //         dealObj=''
        //          obj['limit_min']= ''
        //     }

        //     if (Number(obj.limit_min) > Number(obj.limit_max) && field ==='limit_max'&&event.target.value!=='') {
        //         let tipStr=''
        //         if (obj.type===2) {
        //             tipStr='最多选择项不能小于最少选择项！'
        //         }
        //         if (obj.type===3) {
        //             tipStr='输入最大数不能小于于输入最小数！'
        //         }
        //         this.$message({
        //             message: tipStr,
        //             type: 'warning'
        //         })
        //         dealObj=''
        //         obj['limit_max']= ''
        //     }
        //     if (!field) {
        //         obj.score= dealObj
        //     }
        //     if(field ==='score' && dealObj===''){
        //         obj['score']= ''
        //     }
        //     event.target.value= dealObj
        },
        /*
        @拖动排序
        @parameters updateModel 要更新的题目
        @parameters ids  拖动后的排序
        */
        async saveSort(updateModel, ids) {
            let parameter = {
                modelId: this.template.modelId,
                'questionIds': ids.join(',')
             }
            if (updateModel) {
              parameter.updateQuestionId = updateModel.question_id
              parameter.optionJson = JSON.stringify(updateModel.option_json)
            }
            const res = await this.$api.add.sort.post(parameter)
            if (res.code === 200) {
                // this.$message.success('保存成功')
                this.get()
                this.loading = false
            } else {
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
                this.loading = false
            }
        },

        /* 新增题目
        *  @Parameters type       题目类型 单选多选问答
        *  @Parameters location   位置（索引）n 表示末尾
        */
        addQuestion(type, location) {
            debugger
            const temp = JSON.parse(JSON.stringify(this.addTemplate))
            temp.type = Number(type)
            temp.sort_num = location==='n'?'n':Number(location) + 1
            this.editQuestion(temp, temp.sort_num, 1)
        },
        /* 编辑新增题目
        *  @Parameters question 题目
        *  @Parameters location    位置
        *  @Parameters type     类型 新增1 编辑0 复制 2
         */
        editQuestion(questionOriginal, location, type) {
            debugger
            const question=JSON.parse(JSON.stringify(questionOriginal))
            const _this=this
            const allType={ 1: '单选题',
                            2: '多选题',
                            3: '问答题'}

            const typeText=allType[question.type]
            if (type === 0) {
                question.edit = 1
                question.default==0
                this.dialogTitle = '编辑 [' + typeText + '] 题目'
            } else if (type === 2) {
                question.edit = 1
                question.question_id=''
                question.question_title=question.question_title+'副本'
                this.dialogTitle = '复制 [' + typeText + '] 题目'
                question.option_json.map(item => {
                    item.related=''
                })
            } else {
                this.dialogTitle = '新增 ['+ typeText +'] 题目'
                question.edit = 0
                if (Number(question.type)===2) {
                    question.limit_max = question.option_json.length
                }
            }
            this.form = JSON.parse(JSON.stringify(Object.assign(this.form, question)))
            //单选题默认选中
            if(question.type==1){
                const checkedItemIndex = this.form.option_json.findIndex(item => item.checked);
                if (checkedItemIndex !== -1) {
                    this.form.default = checkedItemIndex;
                } else {
                    console.error("没有选中的选项"); // 错误处理机制
                }
            }
            this.form.sort_num = location
            if (this.form.pic.length>0) {
                this.form.pic.map((item, i) => {
                    const obj={
                        name: 'img'+i,
                        url: item
                    }
                    this.form.pic[i]=obj
                 })
            }
            _this.dialogEdit = true
            this.$nextTick(() => {
                const _this = this
                const tbody = this.$refs.option.$el.querySelector('.el-table__body-wrapper tbody')
                if(tbody){
                    Sortable.create(tbody, {
                        handle: '.move',
                        animation: 300,
                        ghostClass: 'ghost',
                        onEnd ({ newIndex, oldIndex }) {
                            if(oldIndex===_this.form.default){
                                _this.form.default=newIndex
                            }
                            const movedItem = _this.form.option_json.splice(oldIndex, 1)[0];
                            _this.form.option_json.splice(newIndex, 0, movedItem)
                            const newArray = _this.form.option_json.slice(0)
                            _this.form.option_json = []
                            _this.$nextTick(() => {
                                _this.form.option_json = newArray
                                _this.form.option_json.forEach((item,i)=>{
                                    item.value=this.allSN[i]
                                })
                            })
                        }
                    })
                 } 
            })
        },
        clearData() {
            this.form.pic=[]
            console.log(this.form.pic)
        },
        // 打开选项关联题目
        rowSet(question, item, i, index) {
            this.editQuestionInfo = JSON.parse(JSON.stringify(question))
            this.nowRelatedQuestionInfo = '第' + (i + 1) + '题：' + question.question_title + '？ [选项' + this.allSN[index] + ']'
            // 当前编辑项
            this.nowRelatedInfo = item
            // 当前编辑的选项顺序
            this.oldRelatedIndex = index
            // 选中的关联项
            this.relatedQuestion = this.nowRelatedInfo.related === '' || this.nowRelatedInfo.related === undefined ? [] : this.nowRelatedInfo.related.split(',').map(Number)
            this.relatedQuestion2 = this.relatedQuestion
            this.sortData = this.data.filter((item, index) => {
                return index > i && (item.parent === '' || (this.relatedQuestion.includes(item.question_id)||this.relatedQuestion2.includes(item.question_id)))
            })

            if (this.sortData.length === 0) {
                this.$alert('无可关联题目！', '提示', { type: 'warning', closeOnHashChange: !1 })
                return false
            }
            this.dialogRelated = true
            this.index = i + 1
        },
        // 保存[前端]选项关联--调用保存
        saveRelation() {
            if (this.relatedQuestion.length===0) {
              console.log(this.oldRelatedQuestion)
              this.oldRelatedQuestion.map(item => {
                  if (this.idAdd(item.toString())[0]) {
                    this.data[this.idAdd(item.toString())[0] - 1].parent = ''
                  }
              })
            }
            console.log(this.relatedQuestion)
            // 更新关联的父级别
            this.relatedQuestion.map((item, i) => {
                let nowIndex = this.idAdd(item.toString())
                if (nowIndex.length > 0) {
                  console.log(this.data[nowIndex[0] - 1])
                  this.data[nowIndex[0] - 1].parent = this.index
                } else {
                  // 不存在的id
                  this.relatedQuestion.splice(i, 1)
                }
            })

            this.nowRelatedInfo.related = this.relatedQuestion.sort((a, b) => { return a - b }).join(',')
            this.dialogRelated = false
            console.log(this.editQuestionInfo.op)
            this.editQuestionInfo.option_json[this.oldRelatedIndex].related=this.nowRelatedInfo.related
            // 选中的关联项
            this.relatedQuestion = []
            // 保存
            this.optionUpdate(this.editQuestionInfo)
        },
        // 选项关联窗口-清空选择
        clearChanged() {
            // 更新关联的题目
            this.relatedQuestion.map(item => {
                if (this.idAdd(item.toString())[0]) {
                  this.data[this.idAdd(item.toString())[0] - 1].parent = ''
                }
            })
            this.relatedQuestion=[]
            console.log('清空选择')
        },
        handleCheckedOptionChange(value) {
            console.log(value)
            console.log(this.relatedQuestion)
            // this.relatedQuestion.push(value)
        },
        // 查询当前id 所在位置
        idAdd(ids) {
            let nowADD = []
            this.data.map((item, index) => {
                if (ids.split(',').map(Number).includes(item.question_id)) {
                    nowADD.push((index) + 1)
                    // >9?(index) + 1:'0'+((index) + 1)
                }
            })
            return nowADD
        },
        // 选项删除关联--调用保存
        optionDel(question, item, index) {
            console.log(item.related.split(','))

            // 禁用项目不清除
            let disabledOption=[]
            // this.oldRelatedQuestion.map(item => {
            //     const delIndex=this.idAdd(item.toString())[0]
            //     if (delIndex<6) {
            //         disabledOption.push(item)
            //     }
            // })
            item.related.split(',').map(item => {
                const delIndex=this.idAdd(item.toString())[0]
                if (delIndex<8) {
                    disabledOption.push(item)
                } else {
                    this.data[this.idAdd(item.toString())[0] - 1].parent = ''
                }
            })
            item.related = disabledOption.join(',')
            // 保存
            this.optionUpdate(question)
        },
        // 选项更新
        async optionUpdate(question) {
            this.loading = true
            console.log(question)
            const res = await this.$api.add.editOption.post({
                'modelId': question.model_id,
                'questionId': question.question_id,
                'optionJson': JSON.stringify(question.option_json)
            })
            if (res.code === 200) {
                this.$message.success('保存成功')
                // id和位置简历对应
                this.get()
                // console.log(this.data)
            } else {
                this.loading = false
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        },
        // 图片添加删除及上传
        handleChange(file, fileList) {
            this.form.pic=fileList
        },
        handleDel(file, fileList) {
            this.form.pic=fileList
        },
        // 图片预览
        handlePreview(file) {
            this.dialogImageUrl = file.url
            this.dialogImgViewVisible = true
        },
        // 图片上传
        async upImg(file, fileList) {
            this.editLoading = true
            const res = await this.$api.base.imgUpload.post({
                'file': file.file
            })
            if (res.code === 200) {
                this.editLoading = false
                this.form.pic[this.form.pic.length-1].url=res.url
                this.form.pic[this.form.pic.length-1].status='success'
            } else {
                this.editLoading = false
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        },
        // 题目选项删除
        delOption(row, index) {
            if (row.length === 2) {
                this.$message.warning('选择题至少保留2个选项！')
                return false
            }
            row.splice(index, 1)
        },
        // 删除当前题目
        async delQuestion(row, index) {
            if (this.data.length === 1) {
              this.$message.warning('选择题至少保留1个题目！')
              return false
            }
            let parseParams = {
                delQuestionId: row.question_id,
                updateQuestionId: '',
                optionJson: ''
            }
            let idIndex = ''
            let upDateData = ''
            if (row.parent !== '') {
              idIndex = this.idAdd(row.parent.toString())
              upDateData = JSON.parse(JSON.stringify(this.data[idIndex - 1]))
              parseParams.updateQuestionId = upDateData.question_id
              upDateData.option_json.map(item => {
                let temporaryArray = item.related.split(',')
                for (let i = 0; i < temporaryArray.length; i++) {
                    if (Number(temporaryArray[i]) === row.question_id) {
                        temporaryArray.splice(i, 1)
                        break
                    }
                }
                item.related = temporaryArray.join(',')
              })
              parseParams.optionJson = JSON.stringify(upDateData.option_json)
            }

            const res = await this.$api.add.delQuestion.post(parseParams)
            if (res.code === 200) {
                if (row.parent !== '') {
                  // 更新关联的数据
                  this.data[idIndex - 1].option_json=upDateData.option_json
                }
                this.data.splice(index, 1)
                this.$message.success('删除成功')
                this.loading = false
                this.get()
            } else {
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
                this.loading = false
            }
            // this.data.splice(index, 1)
        },
        // 新增题目（插入行）
        pushRow(row) {
            const temp = row || JSON.parse(JSON.stringify(this.addTemplate))
            this.data.push(temp)
        },
        // 新增选项
        rowOption(el) {
            const newOption = {
                'name': '',
                'checked': false,
                'related': '',
                'score': '',
                'value': this.allSN[el.length]
            }
            // 最多6个选项
            if (el.length < 26) {
                el.push(newOption)
            }
        },
        // 输入校验 文档：校验文字<>& {} |*=;%  单行文本框禁止输入英文特殊字符<>&{}|*=;%
        checkText(string) {
            // const pattern = /[`~!@#$^\-&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】'；：""'。，、？\s]/g
            // const pattern = /[`<>& {} |*=;%\s]/g
            const pattern = /[`<>&{}|*=;%]/g
            const str = string.replace(pattern, '')
            this.ruleForm.template_name = str === '.' || str === '' ? '' : str
        },
        checkTextBlur() {
            let string = this.ruleForm.template_name
            const pattern = /[`<>& {}|*=;%]/g
            const str = string.replace(pattern, '').replace(/(^\s*)|(\s*$)/g, '')
            this.ruleForm.template_name = str === '.' || str === '' ? '' : str
        },
        // 预览
        onView() {
          if (this.data.length ===0) {
            this.$alert('至少添加一个题目才能预览!', '提示', { type: 'warning', closeOnHashChange: !1 })
           return false
          }
          this.dialogVisible = true
          this.completeTask = window.location.origin+'/SmartEvaluatePages/mob/index.html#/view?org_id=' + sessionStorage.org_id + '&token='+sessionStorage.token + '&udid=' + sessionStorage.udid + '&mid=' + this.$parent.$parent.editTemplate +'&t=' + new Date().getTime()
          document.getElementById('completeDiv').innerHTML='<iframe ref="myIframe" src="'+this.completeTask+'"  width="100%" style="border:none; height: 100%;"></iframe>'
        },
        close() {
            this.dialogVisible = false
        },
        // 提交(编辑新增题目)
        async onSubmit() {
            // let emptyTitle = false
            // this.$refs['ruleForm'].validate((valid) => {
            //     if (!valid) {
            //         emptyTitle = true
            //     }
            // })
            // if (emptyTitle) {
            //     // this.$alert('请输入题目内容！!', '提示', { type: 'warning' })
            //     return false
            // }
            let emptyQuestion = []
            let allOptionLabel = this.allSN
            let storeQuestion=[]

            if (this.form.question_title.replace(/(\s*$)/g, '') === '') {
                this.$alert('题目不能都为空格!', '提示', { type: 'warning', closeOnHashChange: !1 })
                return false
            }
            if (Number(this.form.type) === 2 || (this.form.type) === 1) {
                // 判断题目是否为空
                this.form.option_json.map((item, index) => {
                    if (item.name.replace(/(\s*$)/g, '') === '') {
                        emptyQuestion.push('选项' + allOptionLabel[index])
                    }

                    if (this.form.type === 1) {
                        const isChecked = index === this.form.default
                        item.checked = isChecked
                        if (this.form.is_score && (item.score =='' && item.score!==0 )) {//|| !storeQuestion
                            storeQuestion.push('选项' + allOptionLabel[index])
                        }
                    }
                })

                if (this.form.type === 2 && this.form.option_json.length <2) {
                    this.$alert('多选题答案不能少于2个!', '提示', { type: 'warning', closeOnHashChange: !1 })
                    return false
                }

                if (this.form.type === 2 && (this.form.limit_min ==='' || this.form.limit_max==='')) {
                    this.$alert('多选题答案个数限制' + (this.form.limit_min ==='' && this.form.limit_max===''?'最小选择数,最大选择数':(this.form.limit_min ===''?'最小选择数':'最大选择数')) + '不能为空!', '提示', { type: 'warning', closeOnHashChange: !1 })
                    return false
                }

                if (storeQuestion.length > 0) {
                    this.$alert(storeQuestion.join(',') + '分数不能为空!', '提示', { type: 'warning', closeOnHashChange: !1 })
                    return false
                }
                if (emptyQuestion.length > 0) {
                    this.$alert(emptyQuestion.join(',') + '不能为空!', '提示', { type: 'warning', closeOnHashChange: !1 })
                    return false
                }


                // 判断重复
                let sum=0
                 
                // 判断选项是否重复
                let allOption={}
                let repeatName=[]
                this.form.option_json.map((ite, index) => {
                   if (ite.name in allOption) {
                      repeatName.push(this.allSN[index])
                   } else {
                     allOption[ite.name]=this.allSN[index]
                   }
                   if(ite.checked){
                    sum+=1
                   }
                })
                if (repeatName.length > 0) {
                    this.$alert(repeatName.join(',') + '选项与上面选项重复!', '提示', { type: 'warning', closeOnHashChange: !1 })
                    return false
                }
                if(sum>this.form.limit_max&&Number(this.form.type) === 2){
                    this.$alert('默认选中项不能超过最大选择数!', '提示', { type: 'warning', closeOnHashChange: !1 })
                    return false
                }
            }

            if (Number(this.form.type) === 3) {
                if (this.form.is_score && ( `${this.form.limit_max}` ==='' || `${ this.form.limit_min}`==='' )) {//|| !storeQuestion
                    this.$alert('问答题计分后输入范围不能为空!', '提示', { type: 'warning', closeOnHashChange: !1 })      
                    return false 
                }
            }

            const loading =this.$loading({
                lock: true,
                });
            // 数据整理
            let saveData = JSON.parse(JSON.stringify(this.form))
            if (saveData.type === 3) {
                saveData.option_json = []
            }

            saveData.option_json = JSON.stringify(saveData.option_json)
            saveData.pic = JSON.stringify(saveData.pic)
            saveData.is_required = saveData.is_required ? 1 : 0
            saveData.is_score = saveData.is_score ? 1 : 0
            saveData.sort_num=saveData.sort_num ==='n'?'':saveData.sort_num + 2
            saveData.model_id=this.template.modelId || sessionStorage.editTemplate
            delete saveData.insert_time
            delete saveData.update_time
            const res = await this.$api.add.addQuestion.post(saveData)

            if (res.code === 200) {
                this.$message.success('保存成功')
                this.get()
                loading.close();
                this.dialogEdit = false
            } else {
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
                loading.close();
            }
        },
        // 返回列表
        back() {
            // 清空模板
            // this.$parent.$parent.editTemplate = null
            // this.$parent.$parent.activeName = 'tabs2Flag'
            // this.$parent.$parent.nowName = '模板列表'
            // this.$parent.$parent.tabsArr.tabs2Flag = true
            // this.$parent.$parent.tabsArr.tabs1Flag = false
            // this.$parent.$parent.tabsArr.tabs3Flag = false
            window.location.href='#x44'
        },
        open() {
            this.$alert('dddddddd', '提示', { type: 'error', closeOnHashChange: !1 })
            // this.$alert('这是一段内容', '标题名称', {
            //   confirmButtonText: '确定',
            //   callback: action => {
            //     this.$message({
            //       type: 'info',
            //       message: `action: ${action}`
            //     });
            //   }
            // });
        },
        handleClose(done) {
            this.$confirm('确认要关闭吗？')
                .then(_ => {
                    done()
                    this.dialogHide()
                })
                .catch(_ => { })
        },
        // 获取模板详情
        async get() {
            this.loading = true
            const res = await this.$api.add.detail.get({
                modelId: this.$parent.$parent.editTemplate,
                evaluator2evaluatedId: ''
            })
            if (res.code === 200) {
                  this.data = res.data.qaVoList
                 this.data.map(item => {
                    item.pic=item.pic === '' ? [] : JSON.parse(item.pic).map(item => item.url)
                    item.parent = ''
                    if (item.type === 2 || item.type === 1) {
                        item.option_json = item.option_json === '' ? [] : JSON.parse(item.option_json)
                        item.option_json.map(it => {
                          console.log(item)
                            if (it.related === undefined) {
                              it.related =''
                            }
                            if (it.related !== '' && it.related !== undefined) {
                                it.related.split(',').map(ite => {
                                    this.$nextTick(() => {
                                        let showQuestion = this.idAdd(ite.toString())
                                        if (showQuestion.length > 0) {
                                          this.data[showQuestion[0] - 1].parent = item.question_id
                                        }
                                    })
                                })
                            }
                        })
                    } else {
                      item.option_json = []
                    }
                    item.is_required = item.is_required === 1
                    item.is_score = item.is_score === 1
                })
                // 更新标题
                this.template.modelId=res.data.model.id
                this.template.modelTitle=res.data.model.model_title
                this.loading = false
                console.log(this.data)
                 this.rowDrop()
            } else {
                this.loading = false
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        }
    }
}
</script>
<style>
.el-textarea .el-input__count {
    background: none;
    bottom: -33px;
    right: 1px;
}

.checkSendObj .el-checkbox,
.el-checkbox__input {
    display: flex;
    position: relative;
    white-space: nowrap;
    align-items: center;
    height: 24px;
    line-height: 24px;
}

.checkSendObj .el-checkbox-group {
    margin-left: 21px;
}

#addWrap .el-dialog__body {
    margin-top: 6px;
    padding-top: 0px;
    min-height: 240px;
}

.el-tree__empty-block {
    max-height: 30px;
}

.userIcon {
    color: #949393;
}

.userIcon i {
    margin-right: 5px;
    margin-left: 5px;
}

.el-dialog {
    min-width: 428px;
}

.el-checkbox-group {
    display: flex;
    padding-top: 8px;
}

.el-checkbox {
    display: flex;
    align-items: center;
}

.el-form-item__content {
    padding-left: 20px;
}
.imgListWrap>.el-form-item__content {
    margin-top: -10px;
}

.el-form-item__error {
    padding-top: 6px;
    top: auto;
    left: 20px;
}

[class*="el-col-"] {
    float: inherit;
}

.el-checkbox__label {
    padding-left: 5px;
}

.el-button--primary {
    color: #fff;
    background-color: #6e6ef1;
    border-color: #6e6ef1;
}

.el-picker-panel__footer button:first-child {
    display: none;
}

/* .el-form .el-input__inner {
    max-width: 300px;
} */

/* /动画/ */
.bounce-enter-active {
    animation: bounce-in 0.5s;
}
.bounce-leave-active {
    animation: bounce-in 0.5s reverse;
}
@keyframes bounce-in {
    0% {
        transform: scale(0);
    }
    50% {
        transform: scale(1.15);
    }
    100% {
        transform: scale(1);
    }
}

.slide-up-enter-active,
.slide-up-leave-active {
    transition: all 0.25s ease-out;
}

.slide-up-enter-from {
    opacity: 0;
    transform: translateY(30px);
}

.slide-up-leave-to {
    opacity: 0;
    transform: translateY(-30px);
}

.el-upload--picture-card{
    width: 72px;
    height: 72px;
    border-radius: 0px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.el-upload--picture-card.el-upload {
  margin-top: 10px;
}
.el-upload-list--picture-card .el-upload-list__item {
    width: 72px;
    height: 72px;
    border-radius: 0px;
}

.imgHide .el-upload--picture-card {
  display: none;
}
</style>
<style scoped type="sass">
.sc-form-table {
    width: 100%;
}

.sc-form-table .sc-form-table-handle {
    text-align: center;
}

.sc-form-table .sc-form-table-handle span {
    display: inline-block;
}

.sc-form-table .sc-form-table-handle button {
    display: none;
}

.sc-form-table .hover-row .sc-form-table-handle-delete span {
    display: none;
}

.sc-form-table .hover-row .sc-form-table-handle-delete button {
    display: inline-block;
}

.el-table td .el-button {
    padding: 8px;
}

.sc-form-table .move {
    text-align: center;
    font-size: 14px;
    margin-top: 3px;
    cursor: move;
}
/* 打印信息 */
.formView {
    line-height: 30px;
}
.formView ul {
    display: flex;
    flex-wrap: wrap;
    padding-top: 0px;
    align-items: center;
}
.formView ul li {
    margin-right: 18px;
    margin-bottom: 10px;
}
.optionShow {
    padding-left: 18px;
    position: relative;
    margin-right: 10px;
}
.optionShow::before {
    content: "□ ";
    font-size: 28px;
    position: absolute;
    left: 0;
    top: -9px;
}

.optionShow.checked::after {
    content: "√ ";
    font-size: 22px;
    position: absolute;
    left: 0;
    top: -7px;
}
.formView .sealWrap {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    height: 190px;
}
.formView .sealWrap .schoolInfo {
    text-align: right;
    position: relative;
    padding: 45px 0 84px;
}
.formView .sealWrap .schoolImg {
    position: absolute;
    right: 26px;
    top: 0px;
    opacity: 0.61;
}
.el-divider {
    background: none;
    border-bottom: 1px #d7d7d7 dotted;
    margin: 6px 0 20px 0;
}
.inputType {
    border-bottom: 1px #000 solid;
    min-width: 100px;
}
.el-divider__text {
    font-size: 14px;
}
.el-form .el-input__inner {
    max-width: 180px;
}
.viewBG {
  padding:70px 22px 81px 22px;
  background: url(~@/assets/bgiphone.png) no-repeat;
  height: 628px;
  width: 340px;
}
.viewWrap {
  margin-top: 5vh!important;
}
iframe::-webkit-scrollbar {
    width: 4px;
}
iframe::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: rgba(0,0,0,0.2);
}
iframe::-webkit-scrollbar-track {
    border-radius: 0;
    background: rgba(0,0,0,0.1);
}

.formWrap{
    /* height: 640px; */
  /* overflow: hidden; */
  width: 100%;
  /* background-size: cover;
  -o-object-fit: cover;
     object-fit: cover;
  -o-object-position: top;
     object-position: top;
  -webkit-mask-image: -webkit-gradient(linear, left top, left bottom, color-stop(63.25%, #000000), color-stop(66.25%, rgba(0, 0, 0, 0.97)), color-stop(69.25%, rgba(0, 0, 0, 0.94)), to(rgba(0, 0, 0, 0)));
  -webkit-mask-image: linear-gradient(180deg, #000000 63.25%, rgba(0, 0, 0, 0.97) 66.25%, rgba(0, 0, 0, 0.94) 69.25%, rgba(0, 0, 0, 0) 100%);
          mask-image: -webkit-gradient(linear, left top, left bottom, color-stop(63.25%, #000000), color-stop(66.25%, rgba(0, 0, 0, 0.97)), color-stop(69.25%, rgba(0, 0, 0, 0.94)), to(rgba(0, 0, 0, 0)));
          mask-image: linear-gradient(180deg, #000000 63.25%, rgba(0, 0, 0, 0.97) 66.25%, rgba(0, 0, 0, 0.94) 69.25%, rgba(0, 0, 0, 0) 100%); */
          background-image: url(~@/assets/background_1.png);
          /* background-repeat: no-repeat;
          max-width: 960px; */
}
/* 模板名称 */
.tempName{
    width: 100%; font-size: 30px; font-weight: normal;
    word-break: break-word;
}
::v-deep .tempName input.el-input__inner {
    height: 50px;
    line-height: 46px;
}
.questionSinggle{
    display: flex;
    align-items: center;
}
.questionLabel {
    width: 30px;
    font-weight: bold;
    padding-left: 10px;
    font-size: 16px;
    position: relative;
}
.is-required .questionLabel::before {
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
    position: absolute;
    left: 0;
    top: 2px;
}
.questionContent {
    font-size: 16px;
    display: flex;
    align-items: center;
}
.questionTip {
    padding: 0px 10px 10px 36px;
    color: #b6b6b6;
    white-space: normal;
    word-break: break-all;
}

.divMove {
  border-radius: 3px;
  /* position: relative; */
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
  border-bottom: 1px #ccc dotted;
   -webkit-transition-property: -webkit-transform;
  transition-property: -webkit-transform;
  transition-property: transform;
  transition-property: transform, -webkit-transform;
  -webkit-transition-duration: 0.3s;
          transition-duration: 0.3s;
  padding: 30px 40px 20px 40px;
  z-index: 1;
  background: #fff;
  cursor: move;
}
.divMove:last-child {
    border: none;
}
.divMove:hover {
  -webkit-transform: scale(1.01);
      -ms-transform: scale(1.01);
          transform: scale(1.01);
  -webkit-box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.07);
          box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.07);
}

.inputs-input {
    margin-top: 9px;
    width: 100%;
    height: 40px;
    padding: 0 20px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border-radius: 3px;
    border: 1px solid #cbd5de;
    -webkit-transition: all 0.2s;
    transition: all 0.2s;
    pointer-events: none;
}

.divMove .tool {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 20px 0 0;
    -webkit-transition-property: -webkit-transform;
    transition-property: -webkit-transform;
    transition-property: transform;
    transition-property: transform, -webkit-transform;
    -webkit-transition-duration: 0.3s;
    transition-duration: 0.3s;
}
.questionWrap {
    padding-bottom: 40px;
}
.questionWrap .tool .tool-item{
    margin:0 10px
}
.questionSelectionTip {
    padding: 20px 40px 0px 40px;
    color: #999;
}
.imagePreviewWrap {
    padding: 0px 30px 10px;
    display: flex;
    flex-wrap: wrap;
    width: 320px;
}
.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
}
.hide,
.imgHide .el-upload--picture-card {
  display: none;
}
.addOptionBtn{
    margin: 5px 0 6px 0
}
.imgListWrap {
    padding-left: 100px;
}
.imgListWrap .el-form-item__content>div {
    display: flex;
}
</style>
